package org.mpremote.android.framework.database;

import android.content.Context;
import android.util.Log;
import org.mpremote.android.framework.MPWebservicesConsumer;
import org.mpremote.android.framework.xml.Album;
import org.mpremote.android.framework.xml.Artist;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Gilad
 * Date: 04/10/2010
 * Time: 00:17:58
 */
public class MPDataManager {

    private final Context applicationContext;
    private final MPWebservicesConsumer webservicesConsumer;
    private final MPDatabaseAccessor databaseAccessor;

    public MPDataManager(Context applicationContext) {
        this.applicationContext = applicationContext;
        this.webservicesConsumer = new MPWebservicesConsumer(applicationContext);
        this.databaseAccessor = new MPDatabaseAccessor(applicationContext);
    }

    public List<Artist> fetchAllArtists(boolean forceRefresh) {
        Log.i(getClass().getSimpleName(), "Fetching all artists");
        List<Artist> artistsList;
        if (forceRefresh) {
            artistsList = webservicesConsumer.getArtistsList().getArtistList();
            databaseAccessor.insertArtists(artistsList);
        } else {
            Log.i(getClass().getSimpleName(), "Trying to fetch from DB");
            artistsList = databaseAccessor.getAllArtists();
            if (artistsList.isEmpty()) {
                Log.i(getClass().getSimpleName(), "DB is empty, fetching from WS");
                artistsList = webservicesConsumer.getArtistsList().getArtistList();
                Log.i(getClass().getSimpleName(), "Parsing complete, Inserting to DB");
                databaseAccessor.insertArtists(artistsList);
            }
        }
        return artistsList;
    }

    public List<Album> fetchAllAlbums(boolean forceRefresh) {
        List<Album> albumList;
        if (forceRefresh) {
            albumList = webservicesConsumer.getAlbumsList().getAlbumList();
            databaseAccessor.insertAlbums(albumList);
        } else {
            albumList = databaseAccessor.getAllAlbums();
            if (albumList.isEmpty()) {
                albumList = webservicesConsumer.getAlbumsList().getAlbumList();
                databaseAccessor.insertAlbums(albumList);
            }
        }
        return albumList;
    }


    public List<Album> fetchAlbumsForArtist(String artistName) {
        Artist artist = databaseAccessor.getArtist(artistName);
        return webservicesConsumer.getAlbumListForArtist(artist.getAlbumsUrl()).getAlbumList();
    }

    public void recreateDatabase() {
        databaseAccessor.recreateDatabase();
    }
}
